package com.yhy.wxzn.wcs.controller;

import java.util.Arrays;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.yhy.wxzn.common.enums.ValidEnums;
import com.yhy.wxzn.wcs.device.plc.bean.FourCarPlc;
import com.yhy.wxzn.wcs.device.rgv.bean.FourWayRgv;
import com.yhy.wxzn.wcs.device.rgv.core.plc.ToRgv;
import com.yhy.wxzn.wcs.device.rgv.enums.PalletStatus;
import com.yhy.wxzn.wcs.device.rgv.enums.ReversingDirection;
import com.yhy.wxzn.wcs.device.rgv.enums.RgvStatus;
import com.yhy.wxzn.wcs.entity.WcsFourWayTask;
import com.yhy.wxzn.wcs.entity.WcsTask;
import com.yhy.wxzn.wcs.enums.TaskStatus;
import com.yhy.wxzn.wcs.service.impl.WcsFourWayTaskServiceImpl;
import com.yhy.wxzn.wcs.service.impl.WcsTaskServiceImpl;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import com.yhy.wxzn.wcs.entity.WcsDeviceInfo;
import com.yhy.wxzn.wcs.service.IWcsDeviceInfoService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

import static com.yhy.wxzn.wcs.SystemInit.fourWayRgvMap;

/**
 * @Description: 设备信息
 * @Author: jeecg-boot
 * @Date: 2023-10-28
 * @Version: V1.0
 */
@RestController
@RequestMapping("/wcs/wcsDeviceInfo")
@Slf4j
public class WcsDeviceInfoController extends JeecgController<WcsDeviceInfo, IWcsDeviceInfoService> {
    @Autowired
    private IWcsDeviceInfoService wcsDeviceInfoService;



    @Autowired
    private WcsTaskServiceImpl taskService;

    /**
     * 分页列表查询
     *
     * @param wcsDeviceInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "设备信息-分页列表查询")
    @ApiOperation(value = "设备信息-分页列表查询", notes = "设备信息-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(WcsDeviceInfo wcsDeviceInfo,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<WcsDeviceInfo> queryWrapper = QueryGenerator.initQueryWrapper(wcsDeviceInfo, req.getParameterMap());
        Page<WcsDeviceInfo> page = new Page<WcsDeviceInfo>(pageNo, pageSize);
        IPage<WcsDeviceInfo> pageList = wcsDeviceInfoService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wcsDeviceInfo
     * @return
     */
    @AutoLog(value = "设备信息-添加")
    @ApiOperation(value = "设备信息-添加", notes = "设备信息-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody WcsDeviceInfo wcsDeviceInfo) {
        wcsDeviceInfo.setStatus(ValidEnums.ENABLE.getValue());
        wcsDeviceInfoService.save(wcsDeviceInfo);
        return Result.OK("添加成功！", wcsDeviceInfo);
    }

    /**
     * 编辑
     *
     * @param wcsDeviceInfo
     * @return
     */
    @AutoLog(value = "设备信息-编辑")
    @ApiOperation(value = "设备信息-编辑", notes = "设备信息-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody WcsDeviceInfo wcsDeviceInfo) {
        wcsDeviceInfoService.updateById(wcsDeviceInfo);
        return Result.OK("编辑成功!", wcsDeviceInfo);
    }



    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "设备信息-通过id删除")
    @ApiOperation(value = "设备信息-通过id删除", notes = "设备信息-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        wcsDeviceInfoService.removeById(id);
        return Result.OK("删除成功!", id);
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "设备信息-批量删除")
    @ApiOperation(value = "设备信息-批量删除", notes = "设备信息-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wcsDeviceInfoService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!", ids);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "设备信息-通过id查询")
    @ApiOperation(value = "设备信息-通过id查询", notes = "设备信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        WcsDeviceInfo wcsDeviceInfo = wcsDeviceInfoService.getById(id);
        if (wcsDeviceInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wcsDeviceInfo);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param wcsDeviceInfo
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WcsDeviceInfo wcsDeviceInfo) {
        return super.exportXls(request, wcsDeviceInfo, WcsDeviceInfo.class, "设备信息");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WcsDeviceInfo.class);
    }

    /**
     * 手自动，解锁 单个切换
     * */
    @RequestMapping(value = "/changeDeviceStatus", method = RequestMethod.POST)
    public Result<?> changeDeviceStatus(HttpServletRequest req, HttpServletResponse resp) {
        String coord = req.getParameter("coord");
        String dealType = req.getParameter("dealType");
        String plcNo = req.getParameter("plcNo");
        String bePort = req.getParameter("bePort");
        if(!StringUtils.isEmpty(coord) && !StringUtils.isEmpty(bePort)){
            return wcsDeviceInfoService.changeDeviceStatus(coord,bePort);
        }else{
            return wcsDeviceInfoService.controlDeviceAll(plcNo,dealType);
        }
    }

//    /**
//     * 手自动，解锁 单个切换
//     * */
//    @RequestMapping(value = "/changeDeviceByCode", method = RequestMethod.POST)
//    public Result<?> changeDeviceByCode(HttpServletRequest req, HttpServletResponse resp) {
//        String deviceCode = req.getParameter("deviceCode");
//        return wcsDeviceInfoService.changeDeviceByCode(deviceCode);
//    }
//
    /**获取设备PLC信息*/
    @GetMapping(value = "/devicePlcInfo")
    public Result<?> devicePlcInfo(@RequestParam(name = "deviceCode", required = true) String deviceId,@RequestParam(name = "deviceType", required = true) String deviceType) {
        return wcsDeviceInfoService.devicePlcInfo(deviceId,deviceType);
    }

    @PostMapping("/interruptRgv/{rgvId}")
    public Result<?> interruptRgv(@PathVariable Integer rgvId) {
        FourWayRgv rgv = fourWayRgvMap.get(rgvId);
        if (rgv == null)
            return Result.error(String.format("未找到id为%s的小车",rgvId));

        rgv.setIntercepted(true);
        return Result.OK(String.format("中断id为%s的小车成功",rgvId));
    }

    @PostMapping("/resetRgv/{rgvId}")
    public Result<?> resetRgv(@PathVariable Integer rgvId) {
        FourWayRgv rgv = fourWayRgvMap.get(rgvId);
        if (rgv == null)
            return Result.error(String.format("未找到id为%s的小车",rgvId));

        rgv.setRgvStatus(RgvStatus.READY);
        ToRgv.getInstance(rgv).clearErrorMsg();

        return Result.OK(String.format("故障恢复id为%s的小车成功",rgvId));
    }

    @PostMapping("/resetRgvAndTask/{rgvId}")
    public Result<?> resetRgvAndTask(@PathVariable Integer rgvId) {
        FourWayRgv rgv = fourWayRgvMap.get(rgvId);
        if (rgv == null)
            return Result.error(String.format("未找到id为%s的RGV",rgvId));

        WcsTask task = taskService.getFirstCanExecuteTask(rgvId);
        if (task == null)
            return Result.error(String.format("当前RGV没有正在执行的任务"));


        if (taskService.updateTaskStatusReturnBool(task, TaskStatus.WAIT)) {
            rgv.setRgvStatus(RgvStatus.READY);
            ToRgv.getInstance(rgv).clearErrorMsg();
            return Result.OK(String.format("恢复RGV和任务成功"));
        }else {
            return Result.error(String.format("恢复RGV和任务失败"));
        }
    }
    @PostMapping("/palletUp/{rgvId}")
    public Result<?> palletUp(@PathVariable Integer rgvId) {
        FourWayRgv rgv = fourWayRgvMap.get(rgvId);
        if (rgv == null)
            return Result.error(String.format("未找到id为%s的RGV",rgvId));

        if (rgv.getCurTask() != null)
            return Result.error(String.format("RGV正在执行任务"));



        PalletStatus palletStatus = rgv.getFourCarPlc().getPalletStatus();
        ReversingDirection reversingDirection = rgv.getFourCarPlc().getReversingDirection();

        if (reversingDirection == ReversingDirection.主通道)
            return Result.error(String.format("当前为主通道，无法顶升"));


        if (palletStatus == PalletStatus.UP)
            return Result.error(String.format("托盘已是顶升状态"));


        ToRgv.getInstance(rgv).palletUp();

        return Result.OK("操作成功");
    }
    @PostMapping("/palletDown/{rgvId}")
    public Result<?> palletDown(@PathVariable Integer rgvId) {
        FourWayRgv rgv = fourWayRgvMap.get(rgvId);
        if (rgv == null)
            return Result.error(String.format("未找到id为%s的RGV",rgvId));

        if (rgv.getCurTask() != null)
            return Result.error(String.format("RGV正在执行任务"));



        PalletStatus palletStatus = rgv.getFourCarPlc().getPalletStatus();
        ReversingDirection reversingDirection = rgv.getFourCarPlc().getReversingDirection();

        if (reversingDirection == ReversingDirection.主通道)
            return Result.error(String.format("当前为主通道，无法下降"));


        if (palletStatus == PalletStatus.DOWN)
            return Result.error(String.format("托盘已是下降状态"));


        ToRgv.getInstance(rgv).palletDown();

        return Result.OK("操作成功");
    }
    @PostMapping("/reversingMainChannel/{rgvId}")
    public Result<?> reversingMainChannel(@PathVariable Integer rgvId) {
        FourWayRgv rgv = fourWayRgvMap.get(rgvId);
        if (rgv == null)
            return Result.error(String.format("未找到id为%s的RGV",rgvId));

        if (rgv.getCurTask() != null)
            return Result.error(String.format("RGV正在执行任务"));



        ReversingDirection reversingDirection = rgv.getFourCarPlc().getReversingDirection();


        if (reversingDirection == ReversingDirection.主通道)
            return Result.error(String.format("换向状态已是主通道"));



        ToRgv.getInstance(rgv).checkDirectAndCommutate(ReversingDirection.主通道);

        return Result.OK("操作成功");
    }
    @PostMapping("/reversingSubChannel/{rgvId}")
    public Result<?> reversingSubChannel(@PathVariable Integer rgvId) {
        FourWayRgv rgv = fourWayRgvMap.get(rgvId);
        if (rgv == null)
            return Result.error(String.format("未找到id为%s的RGV",rgvId));

        if (rgv.getCurTask() != null)
            return Result.error(String.format("RGV正在执行任务"));



        ReversingDirection reversingDirection = rgv.getFourCarPlc().getReversingDirection();


        if (reversingDirection == ReversingDirection.副通道)
            return Result.error(String.format("换向状态已是副通道"));



        ToRgv.getInstance(rgv).checkDirectAndCommutate(ReversingDirection.副通道);

        return Result.OK("操作成功");
    }

}
